package org.itboys.oss;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.GetObjectRequest;
import com.aliyun.openservices.oss.model.OSSObject;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;

/**
 * 阿里云oss相关 多个不同 不同的业务场景 的bucket 定义多个不同的bean <bean id="xxxOssService"
 * class="org.itboys.oss.OssService"> <constructor-arg value="bucket 名字" />
 * <constructor-arg value="endpoint 比如 http://oss-cn-qingdao.aliyuncs.com" />
 * <constructor-arg value="阿里云 accessId" /> <constructor-arg
 * value="阿里云 accessKey" /> </bean>
 * 
 */
public class OssService {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(OssService.class);

	private String bucketName;

	private OSSClient ossClient;

	public OssService(String bucketName, String endpoint, String accessID,
			String accessKey) {
		this.bucketName = bucketName;
		ossClient = new OSSClient(endpoint, accessID, accessKey);
	}

	/**
	 * 上传文件到阿里云
	 * @param data 文件字节 数组
	 * @param fileDir 阿里云oss的目录 传 null 就在默认根目录
	 * @return 传给阿里云的ID 通过ID和目录可以到阿里云OSS CDN 拿图片
	 */
	public String upload(byte[] data, String fileDir) {
		ByteArrayInputStream is = null;
		try {
			is = new ByteArrayInputStream(data);
			Hasher hasher = Hashing.md5().newHasher();
			hasher.putBytes(data);
			String md5Str = hasher.hash().toString();
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(data.length);
			metadata.setUserMetadata(ImmutableMap.of("md5", md5Str));
			String key = getKey();
			String uploadKey = StringUtils.isNotBlank(fileDir) ? fileDir + "/"
					+ key : key;
			PutObjectResult result = ossClient.putObject(bucketName, uploadKey,
					is, metadata);
			Preconditions.checkState(result.getETag().equalsIgnoreCase(md5Str),
					"Oss upload failed: null data or md5 error");
			return key;
		} catch (Exception e) {
			LOGGER.error("upload to aliYun error", e);
			throw new RuntimeException(e);
		} finally {
			IOUtils.closeQuietly(is);
		}
	}
	
	/**
	 * 上传文件到阿里云 不考虑目录
	 * @param data 文件字节 数组
	 * @return 传给阿里云的ID 通过ID和目录可以到阿里云OSS CDN 拿图片
	 */
	public String upload(byte[] data) {
		 return upload(data, null);
	}

	/**
	 * 上传文件到阿里云
	 * @param stream 文件inputStream
	 * @param fileDir 阿里云oss的目录 传 null 就在默认根目录
	 * @return 传给阿里云的ID 通过ID和目录可以到阿里云OSS CDN 拿图片
	 */
	public String upload(InputStream stream, String fileDir) {
		BufferedInputStream bis = null;
		ByteArrayOutputStream baos = null;
		try {
			bis = new BufferedInputStream(stream);
			baos = new ByteArrayOutputStream();
			int c;
			c = bis.read();
			while (c != -1) {
				baos.write(c);
				c = bis.read();
			}
			bis.close();
			byte retArr[] = baos.toByteArray();
			return upload(retArr, fileDir);
		} catch (Exception e) {
			LOGGER.error("upload to aliYun error", e);
			throw new RuntimeException(e);
		} finally {
			IOUtils.closeQuietly(baos);
			IOUtils.closeQuietly(bis);
			IOUtils.closeQuietly(stream);
		}
	}
	
	/**
	 * 上传文件到阿里云 不考虑目录
	 * @param stream 文件inputStream
	 * @return 传给阿里云的ID 通过ID和目录可以到阿里云OSS CDN 拿图片
	 */
	public String upload(InputStream stream) {
		return upload(stream, null);
	}
	
	/**
	 * 下载 阿里云 某个 bucket下的 fileDir 目录 下的 key 文件 到 output 输出流
	 * @param key
	 * @param fileDir
	 * @param output
	 */
	public void download(String key, String fileDir, OutputStream output) {
		OSSObject obj = null;
		try {
			GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, StringUtils.isNotBlank(fileDir) ? fileDir + "/"
					+ key : key);
			obj = ossClient.getObject(getObjectRequest);
			IOUtils.copy(obj.getObjectContent(), output);
		} catch (Exception e) {
			LOGGER.error("download aliYun fail error", e);
		}
	}
	
	/**
	 * 下载 阿里云 某个 bucket下的  根目录 下的 key 文件 到 output 输出流
	 * @param key
	 * @param output
	 */
	public void download(String key, OutputStream output) {
		 download(key, null, output);
	}

	private String getKey() {
		SecureRandom random = new SecureRandom();
		byte bytes[] = new byte[20];
		random.nextBytes(bytes);
		return DigestUtils.sha1Hex(bytes);
	}
}
